package cn.oi.book.pro.service;

import cn.oi.book.pro.model.Knowledge;
import cn.oi.book.pro.repository.KnowledgeRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@RequiredArgsConstructor
public class KnowledgeService {
    private final KnowledgeRepository repository;

    public Page<Knowledge> search(String q, int page, int size) {
        Pageable pageable = PageRequest.of(Math.max(page, 0), Math.max(size, 1));
        if (q == null || q.isBlank()) {
            return repository.findAll(pageable);
        }
        String like = "%" + q.trim() + "%";

        Specification<Knowledge> spec = (root, cq, cb) -> {
            // lower(title) like lower(:like)
            var titleLike = cb.like(cb.lower(root.get("title")), like.toLowerCase());
            // content like :like  (不做 ignore-case，避免对 CLOB 使用 upper/lower)
            var contentLike = cb.like(root.get("content"), like);
            cq.orderBy(cb.desc(root.get("updatedAt")));
            return cb.or(titleLike, contentLike);
        };

        return repository.findAll(spec, pageable);
    }

    public Knowledge save(Knowledge k) { return repository.save(k); }

    public Optional<Knowledge> findById(Long id) { return repository.findById(id); }

    public void delete(Long id) { repository.deleteById(id); }
}
